#include "gpscontroller.h"
#include <QDebug>

/**
 * @brief 构造函数
 * @param parent 父对象指针
 */
GpsController::GpsController(QObject *parent)
    : QObject(parent)
    , m_serialPortManager(new SerialPortManager(this))
    , m_nmeaParser(new NmeaParser(this))
    , m_receivedMessages(0)
    , m_settings(new QSettings("GPSTools", "GPSTools", this))
{
    // 连接串口管理器信号
    connect(m_serialPortManager, &SerialPortManager::lineReceived,
            this, &GpsController::onNmeaLineReceived);
    connect(m_serialPortManager, &SerialPortManager::connectionStatusChanged,
            this, &GpsController::connectionStatusChanged);
    connect(m_serialPortManager, &SerialPortManager::availablePortsChanged,
            this, &GpsController::availablePortsChanged);
    connect(m_serialPortManager, &SerialPortManager::currentPortChanged,
            this, &GpsController::currentPortChanged);
    connect(m_serialPortManager, &SerialPortManager::baudRateChanged,
            this, &GpsController::baudRateChanged);
    connect(m_serialPortManager, &SerialPortManager::errorOccurred,
            this, &GpsController::onSerialError);

    // 连接NMEA解析器信号
    connect(m_nmeaParser, &NmeaParser::gpsDataUpdated,
            this, &GpsController::onGpsDataUpdated);
    connect(m_nmeaParser, &NmeaParser::parseError,
            this, &GpsController::onParseError);

    updateStatusMessage("就绪");
}

// GPS数据访问器实现
double GpsController::latitude() const
{
    return m_currentGpsData.latitude;
}

double GpsController::longitude() const
{
    return m_currentGpsData.longitude;
}

double GpsController::altitude() const
{
    return m_currentGpsData.altitude;
}

double GpsController::speed() const
{
    return m_currentGpsData.speed;
}

double GpsController::course() const
{
    return m_currentGpsData.course;
}

int GpsController::satellites() const
{
    return m_currentGpsData.satellites;
}

QString GpsController::quality() const
{
    return m_currentGpsData.quality;
}

QString GpsController::timestamp() const
{
    return m_currentGpsData.timestamp.toString("yyyy-MM-dd hh:mm:ss");
}

bool GpsController::isValid() const
{
    return m_currentGpsData.isValid;
}

// 串口访问器实现
QStringList GpsController::availablePorts() const
{
    return m_serialPortManager->availablePorts();
}

bool GpsController::isConnected() const
{
    return m_serialPortManager->isConnected();
}

QString GpsController::currentPort() const
{
    return m_serialPortManager->currentPort();
}

int GpsController::baudRate() const
{
    return m_serialPortManager->baudRate();
}

void GpsController::setBaudRate(int rate)
{
    m_serialPortManager->setBaudRate(rate);
}

// 状态访问器实现
QString GpsController::statusMessage() const
{
    return m_statusMessage;
}

int GpsController::receivedMessages() const
{
    return m_receivedMessages;
}

/**
 * @brief 连接到指定串口
 * @param portName 串口名称
 * @param baudRate 波特率
 * @return 连接是否成功
 */
bool GpsController::connectToPort(const QString &portName, int baudRate)
{
    // 提取实际的串口名称（去除描述部分）
    QString actualPortName = portName;
    int spaceIndex = portName.indexOf(' ');
    if (spaceIndex > 0) {
        actualPortName = portName.left(spaceIndex);
    }

    updateStatusMessage(QString("正在连接到 %1...").arg(actualPortName));
    
    bool success = m_serialPortManager->connectToPort(actualPortName, baudRate);
    
    if (success) {
        updateStatusMessage(QString("已连接到 %1 (波特率: %2)")
                           .arg(actualPortName).arg(baudRate));
        m_receivedMessages = 0;
        emit receivedMessagesChanged();
        
        // 保存成功连接的串口信息
        saveLastConnectedPort(actualPortName, baudRate);
    } else {
        updateStatusMessage("连接失败");
    }
    
    return success;
}

/**
 * @brief 断开串口连接
 */
void GpsController::disconnectPort()
{
    m_serialPortManager->disconnectPort();
    updateStatusMessage("已断开连接");
    clearGpsData();
}

/**
 * @brief 刷新可用串口列表
 */
void GpsController::refreshPorts()
{
    m_serialPortManager->refreshPorts();
    updateStatusMessage("串口列表已刷新");
}

/**
 * @brief 清除GPS数据
 */
void GpsController::clearGpsData()
{
    m_currentGpsData = GpsData();
    m_receivedMessages = 0;
    emit gpsDataChanged();
    emit receivedMessagesChanged();
}

/**
 * @brief 获取格式化的坐标字符串
 * @return 格式化的坐标
 */
QString GpsController::getFormattedCoordinates() const
{
    if (!m_currentGpsData.isValid) {
        return "无效坐标";
    }
    
    return QString("纬度: %1°, 经度: %2°")
           .arg(m_currentGpsData.latitude, 0, 'f', 6)
           .arg(m_currentGpsData.longitude, 0, 'f', 6);
}

/**
 * @brief 获取速度（公里/小时）
 * @return 速度值
 */
double GpsController::getSpeedKmh() const
{
    // 将节转换为公里/小时 (1节 = 1.852公里/小时)
    return m_currentGpsData.speed * 1.852;
}

/**
 * @brief 处理GPS数据更新
 * @param gpsData 新的GPS数据
 */
void GpsController::onGpsDataUpdated(const GpsData &gpsData)
{
    m_currentGpsData = gpsData;
    emit gpsDataChanged();
    
    if (gpsData.isValid) {
        updateStatusMessage(QString("GPS定位正常 - %1").arg(gpsData.quality));
    } else {
        updateStatusMessage("GPS信号无效");
    }
}

/**
 * @brief 处理NMEA行数据
 * @param line NMEA数据行
 */
void GpsController::onNmeaLineReceived(const QString &line)
{
    m_receivedMessages++;
    emit receivedMessagesChanged();
    
    // 解析NMEA数据
    m_nmeaParser->parseNmeaLine(line);
    
    // qDebug() << "接收NMEA数据:" << line;
}

/**
 * @brief 处理解析错误
 * @param error 错误信息
 */
void GpsController::onParseError(const QString &error)
{
    updateStatusMessage(QString("解析错误: %1").arg(error));
    emit errorOccurred(error);
    
    qDebug() << "NMEA解析错误:" << error;
}

/**
 * @brief 处理串口错误
 * @param error 错误信息
 */
void GpsController::onSerialError(const QString &error)
{
    updateStatusMessage(QString("串口错误: %1").arg(error));
    emit errorOccurred(error);
    
    qDebug() << "串口错误:" << error;
}

/**
 * @brief 更新状态消息
 * @param message 新的状态消息
 */
void GpsController::updateStatusMessage(const QString &message)
{
    if (m_statusMessage != message) {
        m_statusMessage = message;
        emit statusMessageChanged();
    }
}

/**
 * @brief 保存成功连接的串口信息
 * @param portName 串口名称
 * @param baudRate 波特率
 */
void GpsController::saveLastConnectedPort(const QString &portName, int baudRate)
{
    m_settings->setValue("lastConnectedPort", portName);
    m_settings->setValue("lastConnectedBaudRate", baudRate);
    m_settings->sync();
}

/**
 * @brief 获取上次连接的串口名称
 * @return 上次连接的串口名称
 */
QString GpsController::getLastConnectedPort() const
{
    return m_settings->value("lastConnectedPort", "").toString();
}

/**
 * @brief 获取上次连接的波特率
 * @return 上次连接的波特率
 */
int GpsController::getLastConnectedBaudRate() const
{
    return m_settings->value("lastConnectedBaudRate", 9600).toInt();
}

/**
 * @brief 自动连接到上次成功连接的串口
 * @return 连接是否成功
 */
bool GpsController::autoConnectToLastPort()
{
    QString lastPort = getLastConnectedPort();
    int lastBaudRate = getLastConnectedBaudRate();
    
    if (lastPort.isEmpty()) {
        updateStatusMessage("没有保存的串口信息");
        return false;
    }
    
    // 检查上次连接的串口是否仍然可用
    QStringList availablePorts = m_serialPortManager->availablePorts();
    bool portAvailable = false;
    for (const QString &port : availablePorts) {
        if (port.startsWith(lastPort)) {
            portAvailable = true;
            break;
        }
    }
    
    if (!portAvailable) {
        updateStatusMessage(QString("上次连接的串口 %1 不可用").arg(lastPort));
        return false;
    }
    
    updateStatusMessage(QString("正在自动连接到 %1...").arg(lastPort));
    return connectToPort(lastPort, lastBaudRate);
}
